package com.lagou.edu.service.impl;

import com.lagou.edu.dao.UserDao;

import com.lagou.edu.pojo.UserInfo;
import com.lagou.edu.service.UserService;
import org.hibernate.annotations.DynamicInsert;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.stereotype.Service;



@Service
@DynamicInsert
public class UserServiceImpl implements UserService {

    @Autowired
    private UserDao userDao;

    @Override
    public Integer registerUser(String email, String password, String code) {
        // 是否可以创建用户
        if(!existsUser(email)){
            UserInfo userInfo = new UserInfo();
            userInfo.setEmail(email);
            userInfo.setPassword(password);
            userInfo.setCode(code);
            userDao.saveAndFlush(userInfo);
            return 0;
        }// 超时验证码过期
//        else if(){
//            return 2;
//        }
        else {
            return -1;
        }
    }

    @Override
    public Boolean existsUser(String email) {
        UserInfo userInfo = new UserInfo();
        userInfo.setEmail(email);
        Example<UserInfo> example = Example.of(userInfo);

        boolean exists = userDao.exists(example);
        if(exists){
            return true;
        }else {
            return false;
        }
    }

    @Override
    public Boolean loginUser(String email, String password) {
        // 判断用户是否存在
        if(existsUser(email)){
            // 根据用户邮箱查询密码
            UserInfo user = userDao.findByEmail(email);
            // 判断密码是否正确
            if(password.equals(user.getPassword())){
                return true;
            }else {
                return false;
            }
        }else {
            return false;
        }
    }

}
